<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/8 0008
 * Time: 下午 2:48
 */

namespace app\sports_admin\vaildate;


use app\exception\ParameterException;
use think\Request;
use think\Validate;

class Base extends Validate
{
    /**
     * 检测所有客户端发来的参数是否符合验证类规则
     * 基类定义了很多自定义验证方法
     * 这些自定义验证方法其实，也可以直接调用
     * @throws ParameterException
     * @return true
     */
    public function go_check()
    {
        $params = Request::instance()->param();
        if(!$this->check($params)){
            throw new ParameterException(['msg'=>$this->error,'errorCode'=>400]);
        }
        return true;
    }

    protected function isPositiveInteger($value, $rule = '', $data = '', $field = '')
    {
        if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
            return true;
        }
        return '编号必须是正整数';
    }

    protected function isPositiveString($value, $rule = '', $data = '', $field = '')
    {
        if(is_string($value)){
            return true;
        }
        return $field.'不能为空';
    }

    protected function isNotEmpty($value, $rule = '', $data = '', $field = ''){
        if(!empty($value)){
            return true;
        }
        return $field.'不能为空';

    }


    //手机号的验证规则
    protected function isMobile($value)
    {
        $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
        $result = preg_match($rule, $value);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 验证
     * @param $rule 规则
     * @param $msg 提示信息
     */
    public static function goCheck($rule,$msg)
    {
        $vaildate = new Validate($rule,$msg);
        $params = self::getHttpRequestParams();
        $result = $vaildate->check($params);
        if(!$result){
            throw new ParameterException(['errorCode'=>400,'msg'=>$vaildate->getError()]);
        }
        return true;
    }
    /**
     * 获取请求参数
     */
    private static function getHttpRequestParams()
    {
        return Request::instance()->param();
    }
}